import 'dart:ui';

import 'package:flutter/widgets.dart';


extension ValDoubleAutoSize on double {
  double get w => ValAutoFitScreenSize._getWRpx(this);

  double get h => ValAutoFitScreenSize._getHRpx(this);
}

extension ValAutoIntSize on int {
  double get w => ValAutoFitScreenSize._getWRpx(this * 1.0);

  double get h => ValAutoFitScreenSize._getHRpx(this * 1.0);
}

class ValAutoFitScreenSize {
  ValAutoFitScreenSize._();

  static final ValAutoFitScreenSize _instance = ValAutoFitScreenSize._();

  factory ValAutoFitScreenSize() => _instance;

  late final Size screenSize;
  late final EdgeInsets viewPadding;

  late final double standardWidth; //设计图的宽
  late final double standardHeight; //设计图的高

  static double get screenWidth => _instance.screenSize.width;

  static double get screenHeight => _instance.screenSize.height;

  static double get safeBottomHeight => _instance.viewPadding.bottom;

  static double get safeTopHeight => _instance.viewPadding.top;

  static double get titleBottom => safeTopHeight + 44;

  static double get insertBottom => MediaQueryData.fromWindow(window).viewInsets.bottom;

  // static double get compatibleBottomHeight => safeBottomHeight * 0.5;

  ///兼容IPhone X 之后底部距离
  static EdgeInsets compatibleBottom({EdgeInsets? padding, double ratio = 0.5}) {
    var compatible = EdgeInsets.only(bottom: safeBottomHeight * ratio);
    if (padding != null) {
      compatible = padding + compatible;
    }
    return compatible;
  }

  ///必须初始化
  Future initialize(double standardWidth, double standardHeight) async {
    MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);
    if (mediaQuery.size.isEmpty) {
      return Future.delayed(
        const Duration(milliseconds: 20),
            () async {
          await initialize(standardWidth, standardHeight);
        },
      );
    }
    this.standardWidth = standardWidth;
    this.standardHeight = standardHeight;

    screenSize = mediaQuery.size;
    viewPadding = mediaQuery.viewPadding;
  }

  /// 按照宽rxp来设置
  static double _getWRpx(double size) {
    var result = (screenWidth / _instance.standardWidth * 10000 * size) / 10000;
    result = double.parse(result.toStringAsFixed(3));
    return result;
  }

  /// 按照高rxp来设置
  static double _getHRpx(double size) {
    var result = (screenHeight / _instance.standardHeight * 10000 * size) / 10000;
    result = double.parse(result.toStringAsFixed(3));
    return result;
  }
}
